package net;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 网络编程练习-服务端
 */
public class NetExercise02Server {

    public static void main(String[] args) throws Exception {

        /*
            1)编写客户端程序和服务端程序
            2)客户端可以输入一个音乐文件名，比如 高山流水，服务端收到音乐名后
              可以给客户端返回这个音乐文件，如果服务器没有这个文件，返回一个默认的音乐即可
            3)客户端收到文件后，保存到根目录下
            4)使用StreamUtils
         */

        String parentPath = "D:\\IdeaCode\\javaStudy";
        String defaultMusicPath = "D:\\IdeaCode\\javaStudy\\难忘今宵.mp3";

        ServerSocket serverSocket = new ServerSocket(9999);

        System.out.println("服务端等待请求...");
        Socket socket = serverSocket.accept();

        InputStream inputStream = socket.getInputStream();
        String musicName = StreamUtils.streamToString(inputStream);
        System.out.println("接收到客户端请求：" + musicName);

        File musicFile = new File(parentPath + "\\", musicName + ".mp3");
        OutputStream outputStream = socket.getOutputStream();

        FileInputStream fileInputStream;
        BufferedOutputStream bos = new BufferedOutputStream(outputStream);

        if (!musicFile.exists()) {
            fileInputStream = new FileInputStream(defaultMusicPath);
        } else {
            fileInputStream = new FileInputStream(musicFile);
        }
        byte[] musicData = StreamUtils.streamToByteArray(fileInputStream);
        bos.write(musicData);
        socket.shutdownOutput();//设置结束标记
        System.out.println("服务端文件返回完毕...");

        inputStream.close();
        bos.close();
        socket.close();
        serverSocket.close();


    }
}
